/**  
 * Project Name:api-webhook  
 * File Name:ChsiService.java  
 * Package Name:com.example.service.webhook.business.chsi.service  
 * Date:2016年7月26日下午4:07:19  
 * Copyright (c) 2016, yuandong@51dojo.com All Rights Reserved.  
 *  
*/

package com.example.service.webhook.business.qq.service;

import com.example.service.webhook.business.qq.api.QqClient;
import com.example.service.webhook.business.qq.billitem.QqBillTask;
import com.example.service.webhook.business.qq.dto.*;
import com.example.service.webhook.business.qq.entity.*;
import com.example.service.webhook.business.qq.repository.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * JingdongService <br/>
 * Function: TODO ADD FUNCTION. <br/>
 * Reason: TODO ADD REASON. <br/>
 * Date: 2016年7月26日 下午4:07:19 <br/>
 * 
 * @author yuandong
 * @version
 * @since JDK 1.6
 * @see
 */
@Service
public class QqService {

	private static final Logger LOGGER = LoggerFactory.getLogger(QqService.class);

	@Autowired
	private ThreadPoolTaskExecutor taskExecutor;
	@Autowired
	private QqClient qqClient;
	@Autowired
	private QqUserInfoRepository qqUserInfoRepository;
	@Autowired
	private QqContactRepository qqContactRepository;
	@Autowired
	private QqUserInterestRepository qqUserInterestRepository;
	@Autowired
	private QqRecentContactRepository qqRecentContactRepository;
	@Autowired
	private QqGroupRepository qqGroupRepository;
	@Autowired
	private QqGroupMemberRepository qqGroupMemberRepository;

	/**
	 * 
	 * fetchBill:处理QQ回调 <br/>
	 * 在收到魔蝎的邮箱账单回调时执行<br/>
	 * 基本信息<br/>
	 * 联系人信息<br/>
	 * 兴趣爱好<br/>
	 * 最近联系人信息
	 * QQ群
	 * QQ群的成员信息
	 * @author yuandong
	 * @param task
	 * @since JDK 1.6
	 */
	public void fetchBill(final QqBillTask task) {

		// 这里交给线程池处理，防止下面的业务处理时间太长，导致超时。
		// 超时会导致魔蝎数据进行重试，会收到重复的回调请求

		taskExecutor.execute(new Runnable() {
			@Override
			public void run() {
				try{
					LOGGER.info("start execute qq :{},taskId:{}",task.getQqNum(),task.getTaskId());
					QQData qqData = qqClient.getQQData(task.getTaskId());
					ObjectMapper mapper =new ObjectMapper();
					LOGGER.info(mapper.writeValueAsString(qqData));
					saveUserInfo(task,qqData.getQqUserInfo());
					saveContact(task,qqData.getQqContacts());
					saveUserInterest(task,qqData.getQqPersonalInterestses());
					saveQQRecentContact(task,qqData.getQqRecentContacts());
					saveQQGroup(task,qqData.getQqGroups());
					saveQQGroupMember(task,qqData.getQqGroupMembers());
					LOGGER.info("end execute qq :{},taskId:{}",task.getQqNum(),task.getTaskId());
				}catch(Exception e){
					LOGGER.error("获取QQ数据出现异常",e);
				}
			}
		}

		);

	}

	private void saveUserInfo(QqBillTask task, QQUserInfo userinfo ) {
		try {
//			QQUserInfo userinfo = qqClient.getUserInfo(task.getQqNum());
			if (userinfo != null) {
				QQUserInfoEntity qqUserInfoEntity = new QQUserInfoEntity();
				BeanUtils.copyProperties(userinfo, qqUserInfoEntity);
				qqUserInfoEntity.setUserId(task.getUserId());
				QQUserInfoEntity isExistEntity = qqUserInfoRepository.getUserInfo(task.getUserId(),
						task.getQqNum());
				if (isExistEntity != null) {
					qqUserInfoEntity.setCreateTime(isExistEntity.getCreateTime());
					qqUserInfoEntity.setId(isExistEntity.getId());
					qqUserInfoRepository.updateUserInfo(qqUserInfoEntity);
				} else {
					qqUserInfoRepository.saveUserInfo(qqUserInfoEntity);
				}
			}
		} catch (Exception e) {
			LOGGER.error("保存QQ客户基本信息出现异常", e);
		}

	}
	
	
	private void saveContact(QqBillTask task, List<QQContact> qqContacts) {
		try {
//			List<QQContact> qqContacts = qqClient.getContacts(task.getQqNum());
			if (qqContacts != null) {
				qqContactRepository.deleteQQContact(task.getUserId(),task.getQqNum());
				for(QQContact qqContact:qqContacts){
					QQContactEntity qqContactEntity = new QQContactEntity();
					BeanUtils.copyProperties(qqContact, qqContactEntity);
					qqContactEntity.setUserId(task.getUserId());
					
					qqContactRepository.saveQQContact(qqContactEntity);
				}
				
			}
		} catch (Exception e) {
			LOGGER.error("保存QQ联系人出现异常", e);
		}

	}
	
	private void saveUserInterest(QqBillTask task, List<QQPersonalInterests> qqPersonalInterests) {
		try {
//			List<QQPersonalInterests> qqPersonalInterests = qqClient.getUserInterests(task.getQqNum());
			if (qqPersonalInterests != null) {
				qqUserInterestRepository.deleteUserInterest(task.getUserId(),task.getQqNum());
				for(QQPersonalInterests userInterest:qqPersonalInterests){
					QQPersonalInterestsEntity userInterestEntity = new QQPersonalInterestsEntity();
					BeanUtils.copyProperties(userInterest, userInterestEntity);
					userInterestEntity.setUserId(task.getUserId());
					qqUserInterestRepository.saveUserInterest(userInterestEntity);
				}
				
			}
		} catch (Exception e) {
			LOGGER.error("保存QQ用户兴趣爱好出现异常", e);
		}
	}
	
	private void saveQQRecentContact(QqBillTask task, List<QQRecentContact> qqRecentContacts) {
		try {
//			List<QQRecentContact> qqRecentContacts = qqClient.getQQRecentContact(task.getQqNum());
			if (qqRecentContacts != null) {
				qqRecentContactRepository.deleteQQRecentContact(task.getUserId(),task.getQqNum());
				for(QQRecentContact qqRecentContact:qqRecentContacts){
					QQRecentContactEntity qqRecentContactEntity = new QQRecentContactEntity();
					BeanUtils.copyProperties(qqRecentContact, qqRecentContactEntity);
					qqRecentContactEntity.setUserId(task.getUserId());
					qqRecentContactRepository.saveQQRecentContact(qqRecentContactEntity);
				}
				
			}
		} catch (Exception e) {
			LOGGER.error("保存QQ最近联系人出现异常", e);
		}
	}
	
	
	
	private void saveQQGroup(QqBillTask task, List<QqGroup> qqGroups) {
		try {
//			List<QqGroup> qqGroups = qqClient.getQqGroup(task.getQqNum());
			if (qqGroups != null) {
				qqGroupRepository.deleteQqGroup(task.getUserId(),task.getQqNum());
				for(QqGroup qqGroup:qqGroups){
					QqGroupEntity qqGroupEntity = new QqGroupEntity();
					BeanUtils.copyProperties(qqGroup, qqGroupEntity);
					qqGroupEntity.setUserId(task.getUserId());
					qqGroupRepository.saveQqGroup(qqGroupEntity);
				}
				
			}
		} catch (Exception e) {
			LOGGER.error("保存QQ群组出现异常", e);
		}
	}
	
	private void saveQQGroupMember(QqBillTask task, List<QQGroupMember> qqGroupMemberss) {
		try {
//			List<QQGroupMember> qqGroupMemberss = qqClient.getQQGroupMember(task.getQqNum());
			if (qqGroupMemberss != null) {
				qqGroupMemberRepository.deleteQqGroupMember(task.getUserId(),task.getQqNum());
				for(QQGroupMember qqGroupMember:qqGroupMemberss){
					QQGroupMemberEntity qqGroupEntity = new QQGroupMemberEntity();
					BeanUtils.copyProperties(qqGroupMember, qqGroupEntity);
					qqGroupEntity.setUserId(task.getUserId());
					qqGroupMemberRepository.saveQqGroupMember(qqGroupEntity);
				}
				
			}
		} catch (Exception e) {
			LOGGER.error("保存QQ群组成员信息出现异常", e);
		}
	}

}
